<?php
/**
 * 添加文章的控制器，显示和控制添加页面表单
 */

// Need the utilities file:
require('includes/utilities.inc.php');

// Redirect if the user doesn't have permission:
if (!$user->canCreatePage()) {
	header("Location:index.php");
	exit;
}

// 创建一个新表单，注意，这里用到了HTML_QuickForm2，需要用执行sudo pear install HTML_QuickForm2安装
// 如果引入失败可以插入这行代码，注意，不同系统路径也不同，OpenSUSE的路径是/usr/share/php5/pear：set_include_path(get_include_path() . PATH_SEPARATOR . '/usr/local/pear/share/pear/');
require('HTML/QuickForm2.php');
$form = new HTML_QuickForm2('addPageForm');

// Add the title field:
$title = $form->addElement('text', 'title');
$title->setLabel('文章标题');
$title->addFilter('strip_tags');
$title->addRule('required', '请输入文章标题。');

// Add the content field:
$content = $form->addElement('textarea', 'content');
$content->setLabel('文章内容');
$content->addFilter('trim');
$content->addRule('required', '请输入文章内容.');

// Add the submit button:
$submit = $form->addElement('submit', 'submit', array('value' => '发布文章'));

// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form submission

	// Validate the form data:
	if ($form->validate()) {

		// Insert into the database:
		$q = 'INSERT INTO pages (creatorId, title, content, dateAdded) VALUES (:creatorId, :title, :content, NOW())';
		$stmt = $pdo->prepare($q);
		$r = $stmt->execute(array(':creatorId' => $user->getId(), ':title' => $title->getValue(), ':content' => $content->getValue()));

		// Freeze the form upon success:
		if ($r) {
			$form->toggleFrozen(true);
			$form->removeChild($submit);
		}

	} // End of form validation IF.

} // End of form submission IF.

// Show the page:
$pageTitle = 'Add a Page';
include('includes/header.inc.php');
include('views/add_page.html');
include('includes/footer.inc.php');